package com.student.action;

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.student.entity.User;
import com.student.service.UserService;
import com.student.service.impl.UserServiceImpl;


@WebServlet("/user/*")
public class UserAction extends HttpServlet {
	private static final long serialVersionUID = 1L;
    private UserService userService = new UserServiceImpl();
    
    public UserAction() {
        super();
    }

	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
		//获取指定功能的路径
		String path = request.getPathInfo();
		if("/login.html".equals(path)) {
			//响应登录页面
			request.getRequestDispatcher("/WEB-INF/page/login.jsp").forward(request, response);
		} else if("/login".equals(path)) {
			//获取用户和密码
			String uname = request.getParameter("uname");
			String upassword = request.getParameter("upassword");
			//调用service，判断当前的用户是否存在数据库中，并判断密码是否正确
			User user = new User(uname, upassword);
			boolean flag = userService.checkUser(user);
			if(flag) {
				request.getSession().setAttribute("user", user);
				//如果成功则跳转到学生里面页面
				response.sendRedirect(request.getContextPath() + "/student/list");
			} else {
				//登录失败则重定向到用户登录页面
				response.sendRedirect(request.getContextPath() + "/user/login.html");	
			}
		} else if("/exit".equals(path)) {
			request.getSession().invalidate();
			response.sendRedirect(request.getContextPath() + "/user/login.html");	
		}
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doGet(request, response);
	}

}
